﻿Ext.ns('Ext.ux.tree');
Ext.ux.tree.CheckTreePanel = Ext.extend(Ext.tree.TreePanel, {
    bubbleCheck: true,
    cascadeCheck: true,
    separator: ',',
    initComponent: function(){
        Ext.ux.tree.CheckTreePanel.superclass.initComponent.apply(this, arguments);
        this.on('checkchange', this.onCheckChange, this);
    },
    getValue: function(){
        var a = [];
        this.root.cascade(function(n){
            if (true === n.attributes.checked) {
                a.push(n.id);
            }
        }, this);
        return a;
    },
    clearValue: function(){
        this.root.cascade(function(n){
            n.getUI().toggleCheck(false);
        });
        this.value = [];
        this.getSelectionModel().clearSelections();
        return this;
    },
    setValue: function(val, isKeep){
        this.cascading = true;
        if (isKeep !== true) {
            this.clearValue();
        }
        this.value = this.convertValue.apply(this, val);
        // check nodes
        Ext.each(this.value, function(id){
            var n = this.getNodeById(id);
            if (n) {
                n.getUI().toggleCheck(true);
            }
        }, this);
        this.cascading = false;
        return this.value;
    },
    convertValue: function(val){
        // init return array
        var a = [];
        // calls itself recursively if necessary
        if (1 < arguments.length) {
            for (var i = 0; i < arguments.length; i++) {
                a.push(this.convertValue(arguments[i]));
            }
        }
        else 
            if (Ext.isArray(val)) {
                a = val;
            }
            else 
                if ('number' === typeof val) {
                    a.push(val);
                }
                else 
                    if ('string' === typeof val) {
                        a = val.split(this.separator);
                    }
        return a;
    },
    onCheckChange: function(node, checked){
        if (this.cascading) {
            return;
        }
        this.cascading = true;
        node.bubble(function(n){
            if (checked || (!checked && !n.findChild('checked', true))) {
                n.getUI().toggleCheck(checked);
            }
        });
        node.cascade(function(n){
            n.getUI().toggleCheck(checked);
        });
        this.cascading = false;
    }
});

Ext.reg('checktreepanel', Ext.ux.tree.CheckTreePanel);
